﻿using Basic.HrRemoteModel.DicItem;
using Basic.HrRemoteModel.DicItem.Model;
using Basic.HrRemoteModel.TreeDic;
using Basic.HrRemoteModel.TreeDic.Model;
using WeDonekRpc.CacheClient.Interface;
using WeDonekRpc.Helper;

namespace Basic.FormExtendService.lmpl
{
    [WeDonekRpc.Client.Attr.ClassLifetimeAttr(WeDonekRpc.Client.Attr.ClassLifetimeType.SingleInstance)]
    internal class DictService : IDictService
    {
        private readonly ILocalCacheController _Cache;

        public DictService ( ILocalCacheController cache )
        {
            this._Cache = cache;
        }

        public Dictionary<long, DicItem[]> GetItemNames ( long[] dicId, long[] treeDicId )
        {
            if ( dicId.IsNull() && treeDicId.IsNull() )
            {
                return null;
            }
            string key = "dict_" + string.Join(',', dicId.Add(treeDicId).OrderBy(a => a));
            if ( this._Cache.TryGet(key, out Dictionary<long, DicItem[]> items) )
            {
                return items;
            }
            items = new Dictionary<long, DicItem[]>();
            if ( !dicId.IsNull() )
            {
                DicItemName[] names = new GetDictItemNames
                {
                    DicId = dicId
                }.Send();
                foreach ( IGrouping<long, DicItemName> i in names.GroupBy(a => a.DicId) )
                {
                    items.Add(i.Key, i.Select(c => new DicItem
                    {
                        DicText = c.DicText,
                        DicValue = c.DicValue
                    }).ToArray());
                }
            }
            if ( !treeDicId.IsNull() )
            {
                TreeItemName[] trees = new GetMoreTreeNames
                {
                    DicId = treeDicId
                }.Send();
                foreach ( IGrouping<long, DicItemName> i in trees.GroupBy(a => a.DicId) )
                {
                    items.Add(i.Key, i.Select(c => new DicItem
                    {
                        DicText = c.DicText,
                        DicValue = c.DicValue
                    }).ToArray());
                }
            }
            _ = this._Cache.Add(key, items, new TimeSpan(0, 10, 0));
            return items;
        }
    }
}
